package com.campus.utils;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.campus.properties.AliyunOSSProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Slf4j
@Component
public class AliyunOSSUtil {

    //直接将oss中所有成员变量封装为一个实体类 并利用ioc容器进行自动注入
    @Autowired
    private AliyunOSSProperties aliyunOSSProperties;

    public String upload(byte[] content, String originalFilename) throws Exception {

        //获取oss配置信息
        String endpoint = aliyunOSSProperties.getEndpoint();
        String bucketName = aliyunOSSProperties.getBucketName();
        String region = aliyunOSSProperties.getRegion();

        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();

        // 填写Object完整路径，例如202406/1.png。Object完整路径中不能包含Bucket名称。
        //获取当前系统日期的字符串,格式为 yyyy/MM
        String dir = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM"));
        //生成一个新的不重复的文件名
        String newFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
        String objectName = dir + "/" + newFileName;


        /**
         *         假设今天是2024年6月15日，上传文件名为 avatar.png：
         *         dir: 2024/06
         *         originalFilename: avatar.png
         *         originalFilename.lastIndexOf("."): 6（. 的位置）
         *         originalFilename.substring(6): .png
         *         UUID.randomUUID(): 假设为 123e4567-e89b-12d3-a456-426614174000
         *         newFileName: 123e4567-e89b-12d3-a456-426614174000.png
         *         objectName: 2024/06/123e4567-e89b-12d3-a456-426614174000.png
         *                 这样就生成了一个按日期分类且不会重复的文件存储路径
         */



        // 创建OSSClient实例。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();

        try {
            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(content));
        } finally {
            ossClient.shutdown();
        }

        //    endpoint = "https://oss-cn-beijing.aliyuncs.com";
        /**
         * 分解过程：
         * endpoint.split("//") 结果：["https:", "oss-cn-beijing.aliyuncs.com"]
         * endpoint.split("//")[0]：https:
         * endpoint.split("//")[1]：oss-cn-beijing.aliyuncs.com
         * 最终URL：https://web-tlias.oss-cn-beijing.aliyuncs.com/2024/06/123e4567-e89b-12d3-a456-426614174000.png
         */
        String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + objectName;
        log.info("文件上传成功，返回的url为：{}", url);
        return url;
    }}
